package com.woniuxy.lifeorder.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.life.core.api.CommonResult;
import com.woniuxy.lifeorder.service.entity.BusOrder;
import com.woniuxy.lifeorder.service.entity.BusinessGoods;
import com.woniuxy.lifeorder.service.entity.Orderitem;
import com.woniuxy.lifeorder.service.entity.Ordertype;
import com.woniuxy.lifeorder.service.mapper.*;
import com.woniuxy.lifeorder.service.service.BusOrderService;
import com.woniuxy.lifeorder.service.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author 陈瑜洲，吴继明
 * @since 2020-09-24
 */
@Service
@Transactional
public class BusOrderServiceImpl extends ServiceImpl<BusOrderMapper, BusOrder> implements BusOrderService {
    @Autowired
    private BusOrderMapper busOrderMapper;
    @Autowired
    private OrdertypeMapper ordertypeMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BusinessGoodsMapper businessGoodsMapper;
    @Autowired
    private OrderitemMapper orderitemMapper;
    /**
     *
     * 订单条件查询及分页
     * @param current 当前页
     * @param size   页大小
     * @param busOrder  传回的参数
     * @return
     */
    @Override
    public OrderVO order_query(Integer current, Integer size, BusOrder busOrder) {
        OrderVO orderVO=new OrderVO();
        IPage<BusOrder> page=new Page<>(current,size);
        QueryWrapper qw=new QueryWrapper();
        if(busOrder.getOrderId()!=null){
            qw.eq("ORDER_ID",busOrder.getOrderId());
        }
        if (busOrder.getCreateTime()!=null){
            qw.ge("CREATE_TIME",busOrder.getCreateTime());
        }
        if (busOrder.getFinishTime()!=null){
            qw.le("FINISH_TIME",busOrder.getFinishTime());
        }
        if (StringUtils.isNotBlank(busOrder.getUserId())){
            qw.eq("USER_ID",busOrder.getUserId());
        }
        if (StringUtils.isNotBlank(busOrder.getOutuserId())){
            qw.eq("OUTUSER_ID",busOrder.getOutuserId());
        }
        IPage iPage = busOrderMapper.selectPage(page, qw);
        orderVO.setCurrent(current);
        orderVO.setSize(size);
        orderVO.setTotal(page.getTotal());
        List<BusOrder> records = page.getRecords();

        //注入订单类型对象 注入买家（用户）对象  注入卖家对象
        for (BusOrder b:records) {
            Ordertype ordertype = ordertypeMapper.selectById(b.getOrderTypeId());
            b.setUser(userMapper.selectById(b.getUserId()));
            b.setOutuser(userMapper.selectById(b.getOutuserId()));
            b.setOrdertype(ordertype);
        }
        orderVO.setOrderList(records);
        return orderVO;
    }

    @Override
    public CommonResult order_insert(String userId, String outUserId,Integer orderTypeId, List<BusinessGoods> goods) {
        CommonResult commonResult=new CommonResult();
        BigDecimal p3=null;
        //创建订单对象
        BusOrder busOrder=new BusOrder();
        String orderNumber= UUID.randomUUID().toString().replace("-","").toUpperCase();
        busOrder.setOrderNumber(orderNumber);
        busOrder.setUserId(userId);
        busOrder.setOutuserId(outUserId);
        busOrder.setOrderTypeId(orderTypeId);
        try {
            busOrderMapper.insert(busOrder);
        }catch (Exception e){
            return CommonResult.failed(500L,"订单生成失败");
        }
        //商品数据校验
        for (BusinessGoods b:goods) {
            BusinessGoods businessGoods = businessGoodsMapper.selectById(b.getBusinessId());
            //对比价格
            if (b.getGoodsPrice().compareTo(businessGoods.getGoodsPrice())!=0){
                throw new RuntimeException("商品价格参数异常");
            }
            //对比库存数量
            if (b.getGoodsNum().compareTo(businessGoods.getGoodsNum())!=1){
                throw new RuntimeException("商品数量异常");
            }
            //更新库存
            try {
                businessGoods.setGoodsNum(businessGoods.getGoodsNum()-b.getGoodsNum());
                businessGoodsMapper.updateById(businessGoods);
            }catch (Exception e){
                return CommonResult.failed(500L,e.getMessage());
            }
            //插入订单项数据
            Orderitem orderitem=new Orderitem();
            orderitem.setGoodsId(businessGoods.getGoodsId());
            orderitem.setGoodsNum(b.getGoodsNum());
            orderitem.setOrderitemNumber(UUID.randomUUID().toString().replace("-","").toUpperCase());
            orderitem.setUnitPrice(businessGoods.getGoodsPrice());
            //计算总价
            BigDecimal p1=new BigDecimal(b.getGoodsNum());
            BigDecimal p2=null;
            p2=p1.multiply(businessGoods.getGoodsPrice());
            orderitem.setTotalPrice(p2);
            p3=p3.add(p2);
            //插入订单项
            try {
                orderitemMapper.insert(orderitem);
            }catch (Exception e){
                return CommonResult.failed(500L,e.getMessage());
            }
        }
        return CommonResult.success();
    }
}
